package org.threads.circlebuffer;

/**
 * Thread for obtaining objects stored in CircleBuffer
 * object.
 *
 * @see org.threads.circlebuffer.CircleBuffer
 */
public class ObtainThread extends Thread {

    private CircleBuffer buffer;

    /**
     * Creates an ObtainThread object with specified CircleBuffer.
     * @param buffer circle buffer
     */
    public ObtainThread(CircleBuffer buffer) {
        setBuffer(buffer);
    }

    @Override
    public void run() {

        long threadId = Thread.currentThread().getId();

        try {
            while (true) {
                Object inputMsg = buffer.get();
                String message = "Thread #" + threadId + " has OBTAINED: [" + inputMsg + "]";
                System.out.println(message);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * Used for internal setting the buffer. Don't use straight initialization.
     * @param buffer circle buffer
     */
    private void setBuffer(CircleBuffer buffer) {

        if (buffer == null) {
            throw new IllegalArgumentException(CircleBuffer.CIRCLE_BUFFER_NULL_EX);
        }
        this.buffer = buffer;
    }
}
